<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="Shortcut Icon" href="../../../images/aecc.ico" type="image/x-icon" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="../../../Content/element-plus/index.css">
  <link rel="stylesheet" href="../../../Content/nprogress/nprogress.min.css">
  <link rel="stylesheet" href="../../../styles/vue-page-common.css">
  <script src="../../../Scripts/Array.prototype.flat.js"></script>
  <script src="../../../Scripts/ResizeObserver.js"></script>
  <script src="../../../Content/vue3/vue.global.prod.js"></script>
  <script src="../../../Content/element-plus/index.full.min.js"></script>
  <script src="../../../Content/element-plus/icons-vue.js"></script>
  <script src="../../../Content/element-plus/zh-cn.min.js"></script>
  <script src="../../../Scripts/axios.min.js"></script>
  <script src="../../../Content/nprogress/nprogress.min.js"></script>
  <script src="../../../Scripts/dayjs.min.js"></script>
  <script src="../../../Scripts/axios.config.js"></script>
  <script src="../../../Scripts/crypto-js.min.js"></script>
  <script src="../../../Scripts/secret.js"></script>
  <title>配套单校准</title>
  <style>
    h4 {
      margin: 0;
      font-size: 16px;
      height: 30px;
      line-height: 30px;
      padding: 5px;
    }
  </style>
</head>

<body>
  <div id="app" style="padding: 10px;" v-cloak>
    <el-form :inline="true" :model="dataObj.queryInfo" :label-position="'left'" :disabled="dataObj.disabled">
      <el-form-item label="主制分厂:">
        <el-select v-model="dataObj.queryInfo.factoryid" placeholder="请选择" style="width: 180px;"
          :disabled="dataObj.factoryidDisabled">
          <el-option v-for="item in dataObj.factoryList" :key="item.factoryid" :label="item.factoryname"
            :value="item.factoryid" />
        </el-select>
      </el-form-item>

      <el-form-item label="订单号:">
        <el-autocomplete :prefix-icon="'Search'" v-model.trim="dataObj.queryInfo.mfgordername" placeholder="请输入订单号"
          :trigger-on-focus="false" :fetch-suggestions="getMfgordernameAsync" :value-key="'mfgordername'"
          :debounce="500" style="width:300px;" clearable>
        </el-autocomplete>
      </el-form-item>

      <el-form-item label="零件号:">
        <el-autocomplete :prefix-icon="'Search'" v-model.trim="dataObj.queryInfo.productname" placeholder="请输入零件号"
          :trigger-on-focus="false" :fetch-suggestions="getProductnameAsync" :value-key="'productname'" :debounce="500"
          style="width:300px;" clearable>
        </el-autocomplete>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :icon="'Search'" size="default" @click="getData">查询</el-button>
        <el-button type="primary" :icon="'RefreshRight'" size="default" @click="resetData">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20" style="margin-bottom: 10px;">
      <el-col :span="12">
        <el-card>
          <template #header>
            订单信息
          </template>
          <el-table :data="dataObj.dataList" stripe border v-loading.fullscreen.lock="dataObj.loading"
            :element-loading-text="dataObj.loadingText" element-loading-background="rgba(0,0,0,0.8)" height="350"
            ref="mfgRef" @row-click="handleRowClick">
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column prop="mfgordername" label="生产订单" show-overflow-tooltip></el-table-column>
            <el-table-column prop="productname" label="零件号" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="qty" label="计划数" width="80" show-overflow-tooltip></el-table-column>
            <el-table-column prop="plannedstartdate" label="计划开始时间" width="120" show-overflow-tooltip
              :formatter="splitDate">
            </el-table-column>
            <el-table-column prop="plannedcompletiondate" label="计划完成时间" width="120" show-overflow-tooltip
              :formatter="splitDate">
            </el-table-column>
          </el-table>
          <el-pagination style="margin-top: 10px;" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="dataObj.currentPage" :page-sizes="[dataObj.pageSize,20,50]" :page-size="dataObj.pageSize"
            layout="prev,pager,next,jumper,sizes,total" :total="dataObj.total">
          </el-pagination>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            ERP集件信息
          </template>
          <el-table :data="dataObj.erpBomList" stripe border v-loading.fullscreen.lock="dataObj.loading"
            :element-loading-text="dataObj.loadingText" element-loading-background="rgba(0,0,0,0.8)" height="390"
            ref="erpBomRef">
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column prop="specno" label="工序号" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="specname" label="工序名称" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="productname" label="零件号" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="productbatchno" label="零件批次号" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="qty" label="ERP订单需求数" width="120" show-overflow-tooltip></el-table-column>
            <el-table-column prop="uom" label="计量单位" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="rspos" label="项目编号" width="100" show-overflow-tooltip></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="8">
        <el-card>
          <template #header>
            默认工艺集件信息
          </template>
          <el-table :data="dataObj.mesBomList" stripe border v-loading.fullscreen.lock="dataObj.loading"
            :element-loading-text="dataObj.loadingText" element-loading-background="rgba(0,0,0,0.8)" height="400"
            ref="mesBomRef">
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column prop="specno" label="工序号" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="opdesc" label="工序名称" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="productname" label="零件号" show-overflow-tooltip></el-table-column>
            <el-table-column prop="mesqty" label="MES订单需求数" width="140" show-overflow-tooltip></el-table-column>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card>
          <template #header>
            集件差异信息
          </template>
          <el-table :data="dataObj.bomDiffList" stripe border v-loading.fullscreen.lock="dataObj.loading"
            :element-loading-text="dataObj.loadingText" element-loading-background="rgba(0,0,0,0.8)" height="400"
            ref="bomDiffRef">
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column prop="specno" label="工序号" width="80" show-overflow-tooltip></el-table-column>
            <el-table-column prop="specname" label="工序名称" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="productname" label="零件号" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="diffqty" label="差异数" width="80" show-overflow-tooltip></el-table-column>
            <el-table-column prop="oper_type" label="差异类型" width="100" show-overflow-tooltip>
              <template #default="scope">
                <span v-if="scope.row.oper_type2 === '1'">
                  <el-icon style="margin-right: 5px;">
                    <Top />
                  </el-icon>
                </span>
                <span v-else-if="scope.row.oper_type2 === '2'">
                  <el-icon style="margin-right: 5px;">
                    <Bottom />
                  </el-icon>
                </span>
                <span v-else-if="scope.row.oper_type2 === '3'">
                  <el-icon style="margin-right: 5px;">
                    <circle-plus-filled />
                  </el-icon>
                </span>
                <span v-else>
                  <el-icon style="margin-right: 5px;">
                    <remove-filled />
                  </el-icon>
                </span>
                {{scope.row.oper_type}}
              </template>
            </el-table-column>
            <el-table-column prop="createdate" label="推送时间" width="180" show-overflow-tooltip :formatter="replaceDate">
            </el-table-column>
            <el-table-column prop="send_status" label="推送状态" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="erp_status" label="ERP接收状态" width="100" show-overflow-tooltip>
              <template #default="scope">
                <el-tag :type="scope.row.erp_status === '成功' ? 'success' : 'error'">{{scope.row.erp_status}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="erp_return_date" label="ERP接收时间" width="180" show-overflow-tooltip
              :formatter="replaceDate">
            </el-table-column>
            <el-table-column prop="erp_msg" label="ERP返回消息" width="100" show-overflow-tooltip></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <div style="margin-top: 20px;">
      <el-button :icon="'WarningFilled'" type="warning" @click="resendErp" :disabled="dataObj.disabled">
        重推
      </el-button>
    </div>
  </div>
  <script type="module">
    const { createApp, reactive, ref, toRef, toRefs, onMounted, watch } = Vue
    const { ElMessage, ElLoading, ElMessageBox, ElNotification } = ElementPlus

    const App = {
      setup() {
        const api = '../../../Ashx/ErpSendMESMaterialVue3PageHandler.ashx';

        const mfgRef = ref(null);
        const erpBomRef = ref(null);
        const mesBomRef = ref(null);
        const bomDiffRef = ref(null);

        // 获取分厂列表
        async function getFactoryList() {
          const { data: { data, meta, total } } = await axios({
            url: `../../../Ashx/CommonActionHandle.ashx?actions=getFactory`,
            method: 'POST',
            data: { type: "getFactory" }
          })
          if (meta.status === 500) {
            return ElMessage.error(meta.msg);
          }
          return data;
        }

        // 获取当前用户信息
        async function getUserInfo() {
          const { data: { data, meta, total } } = await axios({
            url: `${api}?actions=getUserInfo`,
            method: 'POST',
            data: { type: "getUserInfo" }
          })
          dataObj.userInfo = data;
          if (meta.status === 500) {
            dataObj.disabled = true;//会话失效，当地登录用户不存在时，禁止对页面进行操作
            return ElMessage.error(meta.msg);
          }
          return data;
        }

        let dataObj = reactive({
          userInfo: {},
          loading: false,
          loadingText: '数据加载中...',
          currentPage: 1,// 当前页
          pageSize: 10, // 每页显示条数
          total: 0,
          factoryidDisabled: false,
          disabled: false,//按钮禁用表示
          queryInfo: {
            mfgordername: '',
            productname: '',
            factoryid: ''
          },
          factoryList: [],
          dataList: [],
          erpBomList: [],
          mesBomList: [],
          bomDiffList: [],
        })

        // 查询数据
        async function getData() {
          dataObj.loading = true;
          dataObj.loadingText = '数据加载中...';
          const { data: { data, meta, total } } = await axios({
            url: `${api}?actions=getMfgorderData`,
            method: 'post',
            data: {
              ...dataObj.queryInfo,
              currentPage: dataObj.currentPage,
              pageSize: dataObj.pageSize,
              type: 'getMfgorderData'
            }
          })
          dataObj.loading = false
          if (meta.status === 500) {
            return ElMessage.error(meta.msg);
          }
          dataObj.dataList = data;
          dataObj.total = total;
        };

        async function handleRowClick(row) {
          const { mfgordername } = row;
          await getErpBomList(mfgordername);
          await getMesBomList(mfgordername);
          await getBomDiffList(mfgordername);
        }

        async function getErpBomList(mfgordername) {
          dataObj.loading = true;
          dataObj.loadingText = '数据加载中...';
          const { data: { data, meta, total } } = await axios({
            url: `${api}?actions=getErp`,
            method: 'post',
            data: { type: 'getErp', mfgordername }
          })
          dataObj.loading = false
          if (meta.status === 500) {
            return ElMessage.error(meta.msg);
          }
          dataObj.erpBomList = data;
        }

        async function getMesBomList(mfgordername) {
          dataObj.loading = true;
          dataObj.loadingText = '数据加载中...';
          const { data: { data, meta, total } } = await axios({
            url: `${api}?actions=getBom`,
            method: 'post',
            data: { type: 'getBom', mfgordername }
          })
          dataObj.loading = false
          if (meta.status === 500) {
            return ElMessage.error(meta.msg);
          }
          dataObj.mesBomList = data;
        }

        async function getBomDiffList(mfgordername) {
          dataObj.loading = true;
          dataObj.loadingText = '数据加载中...';
          const { data: { data, meta, total } } = await axios({
            url: `${api}?actions=getDiff`,
            method: 'post',
            data: { type: 'getDiff', mfgordername }
          })
          dataObj.loading = false
          if (meta.status === 500) {
            return ElMessage.error(meta.msg);
          }
          dataObj.bomDiffList = data;
        }

        // 重推
        async function resendErp() {
          if (dataObj.bomDiffList.length === 0) {
            ElMessage({ type: 'error', message: `订单还未生成集件差异信息，不能重推`, grouping: true });
            return false;
          }

          if (dataObj.bomDiffList.some(i => i.erp_status === '成功')) {
            ElMessage({ type: 'error', message: `集件差异信息已推送成功，不能重推`, grouping: true });
            return false;
          }

          ElMessageBox
            .confirm(`确认要重推吗?`, '确认', { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' })
            .then(async () => {
              const { data: { data, meta, total } } = await axios({
                url: `${api}?actions=resendErp`,
                method: 'post',
                data: { type: 'resendErp', postData: dataObj.bomDiffList, employeename: dataObj.userInfo.EmployeeName }
              })
              if (data) {
                ElMessage({ type: 'success', message: `重推成功`, grouping: true });
                resetData();
              } else {
                ElMessage({ type: 'error', message: meta.msg, grouping: true });
              }
            })
            .catch(() => {
              ElMessage({ type: 'info', message: '已取消' });
            });
        }

        function handleCurrentChange(newPage) {
          dataObj.currentPage = newPage;
          getData();
        };

        function handleSizeChange(newSize) {
          dataObj.pageSize = newSize;
          getData();
        };

        const splitDate = (row, column, cellValue, index) => {
          return cellValue && cellValue.includes('T') ? cellValue.split('T')[0] : cellValue;
        }

        const replaceDate = (row, column, cellValue, index) => {
          return cellValue && cellValue.includes('T') ? cellValue.replace('T', ' ') : cellValue;
        }

        function getMfgordernameAsync(value, callback) {
          fetchSuggestion({ url: '../../../Ashx/CommonActionHandle.ashx', method: 'getMfgordernameAsync', name: 'mfgordername', value, callback });
        }

        function getProductnameAsync(value, callback) {
          fetchSuggestion({ url: '../../../Ashx/CommonActionHandle.ashx', method: 'getProductnameAsync', name: 'productname', value, callback });
        }

        // 输入建议
        const fetchSuggestion = async (config) => {
          const triggerLength = config.triggerLength || 4;
          if (config.value && config.value.length >= triggerLength) {
            const { data: res } = await axios.post(`${config.url}?action=${config.method}`, {
              type: config.method,
              [config.name]: config.value
            })
            if (res.meta.status === 500) {
              return ElMessage.error(res.meta.msg);
            }
            const result = res.data.filter(item => item.rownum < 100);
            config.callback(result);
          }
        }

        // 重置
        function resetData() {
          dataObj.queryInfo = {
            ...dataObj.queryInfo,
            mfgordername: '',
            productname: ''
          };
          dataObj.dataList = [];
          dataObj.erpBomList = [];
          dataObj.mesBomList = [];
          dataObj.bomDiffList = [];
          dataObj.currentPage = 1;
        }

        onMounted(async () => {
          const [userInfo, factoryList] = await Promise.all([
            getUserInfo(),
            getFactoryList()
          ]);
          dataObj.factoryList = factoryList;
          if (userInfo && userInfo.FactoryID) {
            dataObj.queryInfo.factoryid = userInfo.FactoryID;
            dataObj.factoryidDisabled = true;
          }
        })

        return {
          splitDate, replaceDate,
          dataObj,
          handleCurrentChange, handleSizeChange,
          handleRowClick,
          getData, resetData, resendErp,
          mfgRef, erpBomRef, mesBomRef, bomDiffRef,
          getMfgordernameAsync, getProductnameAsync
        }
      }
    };
    const app = createApp(App);
    app.use(ElementPlus, { locale: ElementPlusLocaleZhCn });
    // 注册所有icon
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
      switch (key) {
        default:
          app.component(key, component)
          break;
      }
    }

    app.mount('#app');
  </script>
</body>

</html>